<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="project-child-order-detail">
    <template v-if="!permissionDenied">
      <div :class="{'mobile-el-form': showMobilePage}" class="box">
        <clientInfoComponent
          v-if="clientInfoAuth"
          :order-info="orderInfo"
          :is-project="true"
          :client-info="clientInfo"
          :class="{'dividing' : !showMobilePage}"
        />
        <orderInfoComponent
          :is-project="true"
          :order-info="orderInfo"
          :detail-info="detailInfo"
          :module-type="TAG_MODULES.PROJECT_CHANNEL"
          :class="{'dividing' : !showMobilePage}" />
        <resourceInfo
          v-if="detailInfo && orderInfo"
          ref="resourceInfoRef"
          :order-info="orderInfo"
          :detail-info="detailInfo"
          :configure-detail-info="configureDetailInfo"
          :configure-order-info="configureOrderInfo"
          :class="{'dividing' : !showMobilePage}"
        />
        <publishInfo
          v-if="detailInfo && orderInfo"
          ref="publishInfoRef"
          :order-info="orderInfo"
          :detail-info="detailInfo"
          :class="{'dividing' : !showMobilePage}"
        />
        <!-- <costBreakdownComponent
          v-if="detailInfo && detailInfo"
          :is-project="true"
          :cost-breakdown="costBreakdown"
          :order-info="orderInfo"
          :order-id="orderId"
        /> -->
        <costBreakdownComponent
          v-if="detailInfo && detailInfo"
          ref="costBreakdownRef"
          :cost-breakdown="costBreakdown"
          :order-info="orderInfo"
          :show-settlement-btn="true"
          :order-num="orderInfo.orderId"
          :order-id="orderId"
          :is-detail="true"
          :is-project="true"
          :cost-belong-type="5"
          :project-status="detailInfo.projectStatus"
          style="padding:24px;"
          @update="update"
        />
        <div v-if="hasRouteAuth('crm:project:log')" class="logs-info">
          <Title :title="'操作记录'" style="margin-bottom: 16px;"/>
          <div v-if="operateLogs && operateLogs.length > 0">
            <log-time-line :logs="logList" :edit-api="editLogRemark" @success="editRemarkSuccess" />
            <div v-if="logsNum > 3" class="log-open-btn" @click="switchOpen"> {{ logOpen?'收起':'展开' }}全部记录<i :class="logOpen?'el-icon-arrow-up':'el-icon-arrow-down'"/></div>
          </div>
          <div v-else class="empty-container">
            <img :src="emptyImg" alt="暂无操作日志">
            <div class="empty-text">暂无操作日志</div>
          </div>
        </div>
      </div>
      <fixed-pagination>
        <div class="center">
          <el-button v-if="hasEditAuth" type="primary" size="small" @click="toEdit">编辑订单</el-button>
          <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回</el-button>
        </div>
      </fixed-pagination>
    </template>
    <DeniedPlaceholder v-else class="denied-container"/>
  </div>
</template>
<script>
import orderInfoComponent from '@/components/CreateOrder/orderDetail/orderInfo';
import resourceInfo from '@/components/CreateOrder/orderDetail/resourceInfo';
import clientInfoComponent from '@/components/CreateOrder/orderDetail/clientInfo';
import publishInfo from '@/components/CreateOrder/orderDetail/publishInfo';
import costBreakdownComponent from '@/components/CreateOrder/costList';
import Title from '@/components/Title';
import LogTimeLine from '@/components/Common/logTimeLine';
import projectEditAuth from '@/views/project/projectEditAuth';
import { getProjectOrder } from '@/api/project';
import { getOperateReports, editLogRemark } from '@/api/order';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import emptyImg from '@/assets/empty-data-icon.png';
import { mapState } from 'vuex';
// import { costList } from '@/api/order';

export default {
  name: 'ProjectOrderDetail',
  components: {
    orderInfoComponent,
    resourceInfo,
    publishInfo,
    clientInfoComponent,
    costBreakdownComponent,
    Title,
    LogTimeLine
  },
  mixins: [projectEditAuth],
  data() {
    return {
      TAG_MODULES,
      emptyImg,
      orderId: '',
      projectId: '',
      projectStatus: '',
      permissionDenied: false, // 详情页是否可查看
      orderInfo: {},
      configureDetailInfo: {},
      configureOrderInfo: {},
      costBreakdown: {
        page: 1,
        perPage: 20,
        costList: [],
        total: 0
      },
      detailInfo: null,
      clientInfo: null,
      listLoading: false,
      logOpen: false,
      operateLogs: [],
      miniLogs: [],
      logsNum: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    hasEditAuth() {
      const item = this.detailInfo;
      return this.isEditAuth(item);
    },
    clientInfoAuth() {
      return this.hasRouteAuth('crm:projectInfo:clientInfo') || this.isAdmin;
    },
    logList() {
      return (this.logOpen || this.logsNum <= 3) ? this.operateLogs : this.miniLogs;
    }
  },
  created() {
    this.orderId = Number(this.$route.params.id) || '';
    this.getInfo();
    // this.getCostList();
  },
  methods: {
    editLogRemark,
    hasRouteAuth,
    // 编辑操作日志成功的回调
    editRemarkSuccess() {
      this.getOperateReports();
    },
    update(type, val) {
      this.getInfo();
    },
    getInfo() {
      this.listLoading = true;
      getProjectOrder(this.orderId).then((res) => {
        if (res.data.orderInfo.orderKind && res.data.orderInfo.orderKind.length) res.data.orderInfo.orderKindName = res.data.orderInfo.orderKind.map(i => i.orderKindName).join('，');
        this.listLoading = false;
        this.detailInfo = res.data;
        this.orderInfo = { ...res.data.orderInfo, projectId: res.data.projectId, projectName: res.data.projectName };
        this.getOperateReports();
        // test
        this.orderInfo.priceTable = [{
          name: '含税',
          planPrice: this.orderInfo.planPrice === null ? '--' : (this.orderInfo.planPrice / 100).toFixed(2),
          channelPrice: this.orderInfo.channelPrice === null ? '--' : (this.orderInfo.channelPrice / 100).toFixed(2),
          totalPrice: this.orderInfo.taxAmount === null ? '--' : (this.orderInfo.taxAmount / 100).toFixed(2),
          disabled: false
        }, {
          name: '刊例',
          planPrice: this.orderInfo.articlesPlanPrice === null ? '--' : (this.orderInfo.articlesPlanPrice / 100).toFixed(2),
          channelPrice: this.orderInfo.articlesChannelPrice === null ? '--' : (this.orderInfo.articlesChannelPrice / 100).toFixed(2),
          totalPrice: this.orderInfo.articlesPrice === null ? '--' : (this.orderInfo.articlesPrice / 100).toFixed(2),
          disabled: false
        }, {
          name: '折扣',
          planPrice: this.orderInfo.planDiscountPrice === null ? '--' : this.orderInfo.planDiscountPrice,
          channelPrice: this.orderInfo.channelDiscountPrice === null ? '--' : this.orderInfo.channelDiscountPrice,
          totalPrice: this.orderInfo.discountPrice === null ? '--' : this.orderInfo.discountPrice,
          disabled: true
        }];
        this.clientInfo = res.data.clientInfo;
        this.costBreakdown.costList = res.data.costBreakdown.costList;
        this.$nextTick(() => {
          if (this.$refs.costBreakdownRef) this.$refs.costBreakdownRef.insertDetail(res.data.costBreakdown);
        });
      }).catch(e => {
        if (e.code === 403) {
          this.permissionDenied = true;
        }
        this.listLoading = false;
        console.error(e);
      });
    },
    toEdit() {
      this.$router.push({
        name: 'editProjectChild',
        params: { id: this.orderId }
      });
    },
    toBack() {
      this.$router.push({
        name: 'projectChild'
      });
    },
    switchOpen() {
      this.logOpen = !this.logOpen;
    },
    // 获取操作日志列表
    getOperateReports() {
      const data = {
        id: this.orderId,
        type: 0
        // notShowNoAuthTip: true
      };
      getOperateReports(data).then(res => {
        if (res.code === 200) {
          this.operateLogs = res.data;
          const totalLogs = res.data ? JSON.parse(JSON.stringify(res.data)) : [];
          let logsNum = 0;
          totalLogs.forEach(i => {
            logsNum += i.operations.length;
          });
          this.logsNum = logsNum;
          if (logsNum > 3) {
          // 获取折叠后的数据
            const miniLogItem = [];
            for (let i = 0; i < totalLogs.length; i++) {
              if (miniLogItem.length >= 3) break;
              for (let j = 0; j < totalLogs[i].operations.length; j++) {
                totalLogs[i].operations[j].operationTime = totalLogs[i].operationTime;
                miniLogItem.push(totalLogs[i].operations[j]);
                if (miniLogItem.length >= 3) break;
              }
            }
            const miniLogs = [];
            miniLogItem.forEach(i => {
              const a = miniLogs.find(j => j.operationTime === i.operationTime);
              if (a) {
                a.operations.push(i);
              } else {
                miniLogs.push({
                  operationTime: i.operationTime,
                  operations: [i]
                });
              }
            });
            this.miniLogs = miniLogs;
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.project-child-order-detail {
  padding: 16px;
  &.mobile-detail-wrap {
    padding: 0;
  }
  .btn-box {
    margin-top: 24px;
  }
  .box {
    // background-color: #FBFBFD;
    overflow: hidden;
    padding-bottom: 80px;
    position: relative;
    background-color: #fff;
    &::v-deep {
      .dividing{
        .el-col {
          .el-form-item__content {
            border-right: 1px solid #EBEEFD;
          }
          &:nth-child(3n) {
            .el-form-item__content {
              border-right: none;
            }
          }
          &:last-child {
            .el-form-item__content {
              border-right: none;
            }
          }
        }
      }
    }
    .el-row {
      & ::v-deep {
        .el-form {
          .el-form-item {
            margin-bottom: 0px !important;
            padding-right: 10px;
            .el-form-item__content {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
      }
    }
    .logs-info {
      padding: 0 24px;
    }
    .empty-container {
      text-align: center;
      position: relative;
      margin-top: 20px;
      img {
        width: 90px;
      }
      .empty-text {
        color: #999;
        max-width: 300px;
        font-size: 14px;
        margin: 0 auto;
      }
    }
    .log-open-btn {
      display:flex;
      justify-content:center;
      color: #333333;
      font-size:14px;
      cursor: pointer;
      align-items: center;
      margin-top: 10px;
      i {
        margin-left: 8px;
      }
    }
  }
  .denied-container {
    height: calc(100vh - 80px);
    justify-content: flex-start;
    padding-top: 100px;
  }
}
</style>
